<template>
    <a-modal
        v-model:open="showSelectImage"
        title="武器图片选择"
        centered
        width="75vmin"
        :footer="null"
    >
        <div class="imageSelectList">
            <div class="imageSelectItem" v-for="(item, index) in weaponImgList" :key="index" @click="selectImage(item)">
                <img :src="item.img" :alt="item.name">
            </div>
        </div>
    </a-modal>
    <a-modal
        v-model:open="showCreateMod"
        title="创建mod"
        centered
        @ok="createMod"
        width="60vmin"
    >
        <div class="modCreateForm">
            <a-form ref="createFormRef" :rules="rules1" :model="createFormState" :wrapper-col="wrapperCol">
                <a-form-item label="mod名称" name="name">
                    <a-input v-model:value="createFormState.name" placeholder="请输入mod名称" />
                </a-form-item>
                <a-form-item label="作者" name="author">
                    <a-input v-model:value="createFormState.author" placeholder="请输入作者名称" />
                </a-form-item>
                <a-form-item label="mod描述" name="desc">
                    <a-textarea v-model:value="createFormState.desc" placeholder="请输入mod描述" :rows="3" />
                </a-form-item>
            </a-form>
        </div>
    </a-modal>
    <a-modal
        v-model:open="showEditModInfo"
        title="编辑mod信息"
        centered
        @ok="editModInfo"
        width="60vmin"
    >
        <div class="modCreateForm">
            <a-form ref="editFormRef" :rules="rules1" :model="createFormState" :wrapper-col="wrapperCol">
                <a-form-item label="mod名称" name="name">
                    <a-input v-model:value="createFormState.name" placeholder="请输入mod名称" />
                </a-form-item>
                <a-form-item label="作者" name="author">
                    <a-input v-model:value="createFormState.author" placeholder="请输入作者名称" />
                </a-form-item>
                <a-form-item label="mod描述" name="desc">
                    <a-textarea v-model:value="createFormState.desc" placeholder="请输入mod描述" :rows="3" />
                </a-form-item>
            </a-form>
        </div>
    </a-modal>
    <a-modal
        v-model:open="showCreateSpell"
        title="创建新法术"
        centered
        @ok="handleCreateNewSpell"
        width="40vmin"
    >
        <div class="modCreateForm">
            <a-form ref="createSpellFormRef" :model="createSpellFormState" :wrapper-col="wrapperCol">
                <a-select v-model:value="createSpellFormState.type" style="width: 100%;" placeholder="请选择法术类型">
                    <a-select-option v-for="(item, index) in spellTemplateList" :key="index" :value="item.value">
                        {{ item.label }}
                    </a-select-option>
                </a-select>
            </a-form>
        </div>
    </a-modal>
    <div class="kdModCreate fc">
        <div class="modList">
            <div class="title df ai-c">
                {{ showOtherMod ? (showReviewMod ? '待审核mod列表' : '社区mod列表') : `本地mod列表` }}
                <div class="tipButton ml" @click="handleShowTip">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" class="bi bi-question-circle" viewBox="0 0 16 16">
                        <path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z"/>
                        <path d="M5.255 5.786a.237.237 0 0 0 .241.247h.825c.138 0 .248-.113.266-.25.09-.656.54-1.134 1.342-1.134.686 0 1.314.343 1.314 1.168 0 .635-.374.927-.965 1.371-.673.489-1.206 1.06-1.168 1.987l.003.217a.25.25 0 0 0 .25.246h.811a.25.25 0 0 0 .25-.25v-.105c0-.718.273-.927 1.01-1.486.609-.463 1.244-.977 1.244-2.056 0-1.511-1.276-2.241-2.673-2.241-1.267 0-2.655.59-2.75 2.286zm1.557 5.763c0 .533.425.927 1.01.927.609 0 1.028-.394 1.028-.927 0-.552-.42-.94-1.029-.94-.584 0-1.009.388-1.009.94z"/>
                    </svg>
                </div>
            </div>
            <a-spin :spinning="modListLoading">
                <div class="modListBox" :style="{ paddingTop: showList.length == 0 ? '10vmin' : '' }">
                <div v-if="showOtherMod" class="buttons df ai-c jc-se">
                    <div v-if="isDev" class="button" @click="handleShowReviewMod">{{ showReviewMod ? '切换社区mod' : '切换待审核mod' }}</div>
                    <div class="button" @click="handleShowOtherMod(false)">返回mod制作</div>
                </div>
                <div v-else class="buttons df ai-c jc-se">
                    <div class="button" @click="showCreateMod = true">创建mod</div>
                    <div class="button" @click="importMod">导入mod</div>
                    <div class="button" @click="handleShowOtherMod(true)">社区mod</div>
                </div>
                <a-collapse v-for="(item, index) in showList" v-model:activeKey="activeKey" :key="index" accordion :bordered="false">
                    <a-collapse-panel :key="index" :header="showOtherMod ? item.OtherModName : (item.mod ? item.mod.name : '')">
                        <div v-if="!showOtherMod" class="df ai-c modWeaponItem" @click="handleCreateNewWeapon(index)">
                            <plus-outlined></plus-outlined>
                            <div class="ml">添加新武器</div>
                        </div>
                        <div v-if="!showOtherMod" class="df ai-c modWeaponItem" @click="handleCreateNewSpellModal(index)">
                            <plus-outlined></plus-outlined>
                            <div class="ml">添加新法术</div>
                        </div>
                        <template v-if="item.mod.weapons && item.mod.weapons.length">
                            <div class="modClassTitle mt" style="color: #da1067;">武器列表</div>
                            <div v-for="(weaponItem, weaponIndex) in item.mod.weapons" :key="weaponIndex" class="df ai-c jc-sb modWeaponItem" @click="handleEditWeapon(index, weaponIndex)">
                                <div class="light-bar light1" :class="{ show: targetEditModIndex == index && targetEditWeaponIndex == weaponIndex }"></div>
                                <div class="light-bar light2" :class="{ show: targetEditModIndex == index && targetEditWeaponIndex == weaponIndex }"></div>
                                <div class="light-bar light3" :class="{ show: targetEditModIndex == index && targetEditWeaponIndex == weaponIndex }"></div>
                                <div class="light-bar light4" :class="{ show: targetEditModIndex == index && targetEditWeaponIndex == weaponIndex }"></div>
                                <div class="df ai-c">
                                    <img class="weaponImg" :src="weaponItem.img" :alt="weaponItem.znName">
                                    {{ weaponItem.znName }}
                                </div>
                                <div v-if="!showOtherMod" class="button err" @click.stop="handleDeleteWeapon(index, weaponIndex)">删除武器</div>
                            </div>
                        </template>
                        <template v-if="item.mod.spell && item.mod.spell.length">
                            <div class="modClassTitle mt" style="color: #1677ff;">法术列表</div>
                            <div v-for="(spell, spellIndex) in item.mod.spell" :key="spellIndex" class="df ai-c jc-sb modWeaponItem" @click="handleEditSpell(index, spellIndex)">
                                <div class="light-bar light1" :class="{ show: targetEditModIndex == index && targetEditSpellIndex == spellIndex }"></div>
                                <div class="light-bar light2" :class="{ show: targetEditModIndex == index && targetEditSpellIndex == spellIndex }"></div>
                                <div class="light-bar light3" :class="{ show: targetEditModIndex == index && targetEditSpellIndex == spellIndex }"></div>
                                <div class="light-bar light4" :class="{ show: targetEditModIndex == index && targetEditSpellIndex == spellIndex }"></div>
                                <div class="df ai-c">
                                    <img class="weaponImg" :src="spell.params.SpellsImage" :alt="spell.params.name">
                                    {{ spell.params.name }}
                                </div>
                                <div v-if="!showOtherMod" class="button err" @click.stop="handleDeleteSpell(index, spellIndex)">删除法术</div>
                            </div>
                        </template>
                        <div v-if="showOtherMod" class="df ai-c jc-se mt">
                            <div v-if="showReviewMod" class="button" @click="checkModSuccess(item.id)">审核通过</div>
                            <div v-if="showReviewMod" class="button err" @click="checkModDelete(item.id)">删除审核</div>
                            <div v-if="showOtherMod && !showReviewMod" class="button err" @click="otherModListDelete(item.id)">删除mod</div>
                            <div class="button" @click="exportMod(index)">下载mod</div>
                        </div>
                        <div v-else class="df ai-c jc-se mt">
                            <div class="button" @click="handleShowEditModInfo(index)">编辑</div>
                            <div class="button" @click="exportMod(index)">导出</div>
                            <div class="button" @click="handleUploadMod(index)">发布</div>
                            <div class="button err" @click="handleDeleteMod(index)">删除mod</div>
                        </div>
                    </a-collapse-panel>
                </a-collapse>
                <a-empty v-if="showList.length == 0" :description="showOtherMod ? (showReviewMod ? '暂无待审核mod' : '这里空空的...') :`暂无数据`" />
                </div>
            </a-spin>
        </div>
        <div class="kdWeaponCreate" v-show="hasCreateWeapon">
            <div class="title">Kinky Dungeon 自定义武器</div>
            <div class="form">
                <a-form ref="formRef" :rules="rules" :model="formState" :wrapper-col="wrapperCol">
                    <a-form-item label="武器名称(不要包含空格)" name="znName">
                        <a-input v-model:value="formState.znName" placeholder="请输入武器名称" />
                    </a-form-item>
                    <a-form-item label="英文名称(不要包含空格,建议驼峰式命名)" name="enName">
                        <a-input v-model:value="formState.enName" placeholder="请输入英文名称" />
                    </a-form-item>
                    <a-form-item label="武器描述" name="desc">
                        <a-textarea v-model:value="formState.desc" placeholder="请输入武器描述(如:包含高级咒语和饥渴魔法师的惊险故事。普通攻击无法暴击。)" :rows="4" />
                    </a-form-item>
                    <a-form-item label="武器性能描述" name="desc2">
                        <a-textarea v-model:value="formState.desc2" placeholder="请输入武器性能描述(如:造成暗影伤害。)" :rows="4" />
                    </a-form-item>
                    <a-form-item label="武器攻击描述" name="atkDesc">
                        <a-textarea v-model:value="formState.atkDesc" placeholder="请输入武器攻击描述(如:使用矛进行远程攻击。)" :rows="2" />
                    </a-form-item>
                    <a-form-item label="武器图片" name="img">
                        <a-upload
                            name="avatar"
                            list-type="picture-card"
                            class="avatar-uploader"
                            :show-upload-list="false"
                            :customRequest="handleUpload"
                            :maxCount="1"
                        >
                            <img v-if="formState.img" :src="formState.img" alt="武器图片" />
                            <div v-else>
                                <loading-outlined v-if="uploadLoading"></loading-outlined>
                                <plus-outlined v-else></plus-outlined>
                                <div class="ant-upload-text">上传图片</div>
                            </div>
                        </a-upload>
                        <div class="tip">请上传png格式的图片，比例1/1，宽高70px左右</div>
                        <div class="link" @click="showSelectImage = true">使用kd自带武器图片</div>
                    </a-form-item>
                    <a-form-item label="伤害(示例：徒手20 矛40)" name="damage">
                        <a-input-number class="numberBox" v-model:value="formState.damage" :precision="0" placeholder="请输入武器伤害" :min="1" :max="1000" />
                    </a-form-item>
                    <a-form-item label="命中率(%)" name="chance">
                        <a-input-number class="numberBox" placeholder="请输入武器命中率" :precision="0" v-model:value="formState.chance" :min="1" :max="200"/>
                    </a-form-item>
                    <a-form-item label="伤害类型" name="type">
                        <a-select v-model:value="formState.type" placeholder="请选择伤害类型">
                            <a-select-option v-for="(item, index) in KinkyDungeonWeaponsTypeList" :key="index" :value="item.id">
                                {{ item.name }}
                            </a-select-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="武器音效" name="sfx">
                        <a-select v-model:value="formState.sfx" placeholder="请选择武器音效">
                            <a-select-option v-for="(item, index) in KinkyDungeonWeaponsSfxList" :key="index" :value="item.id">
                                {{ item.name }}
                            </a-select-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="武器词条" name="tags">
                        <a-select
                            v-model:value="formState.tags"
                            mode="multiple"
                            style="width: 100%"
                            placeholder="请选择武器词条"
                            :options="KinkyDungeonWeaponsTagsList"
                        ></a-select>
                    </a-form-item>
                    <a-form-item label="耐力消耗(示例：刀15 斧头30)" name="staminacost">
                        <a-input-number class="numberBox" v-model:value="formState.staminacost" :precision="0" placeholder="请输入耐力消耗" :min="0" :max="1000" />
                    </a-form-item>
                    <a-form-item v-if="!formState.heavy" label="轻型武器">
                        <a-radio-group v-model:value="formState.light">
                            <a-radio :value="true">是</a-radio>
                            <a-radio :value="false">否</a-radio>
                        </a-radio-group>
                    </a-form-item>
                    <a-form-item v-if="!formState.light" label="重型武器">
                        <a-radio-group v-model:value="formState.heavy">
                            <a-radio :value="true">是</a-radio>
                            <a-radio :value="false">否</a-radio>
                        </a-radio-group>
                    </a-form-item>
                    <a-form-item v-if="!formState.light" label="双手(作为主要武器时不能使用副手武器，手臂被绑住时无法使用)">
                        <a-radio-group v-model:value="formState.clumsy">
                            <a-radio :value="true">是</a-radio>
                            <a-radio :value="false">否</a-radio>
                        </a-radio-group>
                    </a-form-item>
                    <a-form-item label="不可暴击">
                        <a-radio-group v-model:value="formState.nocrit">
                            <a-radio :value="true">是</a-radio>
                            <a-radio :value="false">否</a-radio>
                        </a-radio-group>
                    </a-form-item>
                    <a-form-item v-if="!formState.nocrit" label="暴击伤害(%)" name="crit">
                        <a-input-number class="numberBox" v-model:value="formState.crit" :precision="0" placeholder="请输入武器暴击伤害" :min="100" :max="1000" />
                    </a-form-item>
                    <a-form-item label="在体力值超过50%时 造成伤害增加">
                        <a-radio-group v-model:value="formState.hasStam50mult">
                            <a-radio :value="true">是</a-radio>
                            <a-radio :value="false">否</a-radio>
                        </a-radio-group>
                    </a-form-item>
                    <a-form-item v-if="formState.hasStam50mult" label="在体力值超过50%时造成伤害比例(斧头150% 魔法锤200%)" name="stam50mult">
                        <a-input-number class="numberBox" v-model:value="formState.stam50mult" placeholder="请输入伤害比例" :precision="0" :min="100" :max="1000" />
                    </a-form-item>
                    <a-form-item label="切割加成(剑1% 断线钳30%)">
                        <a-input-number class="numberBox" placeholder="请输入切割加成(%)" v-model:value="formState.cutBonus" :min="0" :max="100" />
                    </a-form-item>
                    <a-form-item label="魔法武器">
                        <a-radio-group v-model:value="formState.magic">
                            <a-radio :value="true">是</a-radio>
                            <a-radio :value="false">否</a-radio>
                        </a-radio-group>
                    </a-form-item>
                    <a-form-item label="是否施加束缚">
                        <a-radio-group v-model:value="formState.addBind">
                            <a-radio :value="true">是</a-radio>
                            <a-radio :value="false">否</a-radio>
                        </a-radio-group>
                    </a-form-item>
                    <a-form-item v-if="formState.addBind" label="束缚值(绳索50 粘液剑25)" name="bind">
                        <a-input-number class="numberBox" v-model:value="formState.bind" :precision="0" placeholder="请输入束缚值" :min="0" :max="1000" />
                    </a-form-item>
                    <a-form-item v-if="formState.addBind" label="施加束缚类型" name="bindType">
                        <a-select v-model:value="formState.bindType" placeholder="请选择施加束缚类型">
                            <a-select-option v-for="(item, index) in bindTypeList" :key="index" :value="item.id">
                                {{ item.name }}
                            </a-select-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item v-if="formState.addBind" label="束缚效率(粘液剑0% 仲裁者125% 胶带杖200%)" name="bindEff">
                        <a-input-number class="numberBox" v-model:value="formState.bindEff" :precision="0" placeholder="请输入束缚效率" :min="0" :max="1000" />
                    </a-form-item>
                    <a-form-item v-if="formState.addBind" label="束缚暴击倍率(仲裁者200%)" name="bindcrit">
                        <a-input-number class="numberBox" v-model:value="formState.bindcrit" :precision="0" placeholder="请输入束缚暴击倍率" :min="100" :max="1000" />
                    </a-form-item>
                    <a-form-item label="无伤害衰减(不会因为低体力或被束缚而减少伤害)">
                        <a-radio-group v-model:value="formState.noDamagePenalty">
                            <a-radio :value="true">是</a-radio>
                            <a-radio :value="false">否</a-radio>
                        </a-radio-group>
                    </a-form-item>
                    <a-form-item label="无需手持">
                        <a-radio-group v-model:value="formState.noHands">
                            <a-radio :value="true">是</a-radio>
                            <a-radio :value="false">否</a-radio>
                        </a-radio-group>
                    </a-form-item>
                    <a-form-item label="对脆弱目标不会造成额外伤害">
                        <a-radio-group v-model:value="formState.novulnerable">
                            <a-radio :value="true">是</a-radio>
                            <a-radio :value="false">否</a-radio>
                        </a-radio-group>
                    </a-form-item>
                    <a-form-item v-if="!formState.isRange" label="点燃目标">
                        <a-radio-group v-model:value="formState.ignite">
                            <a-radio :value="true">是</a-radio>
                            <a-radio :value="false">否</a-radio>
                        </a-radio-group>
                    </a-form-item>
                    <a-form-item v-if="!formState.ignite" label="可远程攻击(参考矛)">
                        <a-radio-group v-model:value="formState.isRange">
                            <a-radio :value="true">是</a-radio>
                            <a-radio :value="false">否</a-radio>
                        </a-radio-group>
                    </a-form-item>
                    <a-form-item v-if="!formState.ignite && formState.isRange" label="攻击范围(矛2 长矛3)" name="range">
                        <a-input-number class="numberBox" v-model:value="formState.range" :precision="0" placeholder="请输入攻击范围" :min="2" :max="100" />
                    </a-form-item>
                    <a-form-item label="是否有特殊效果">
                        <a-radio-group v-model:value="formState.hasEvents">
                            <a-radio :value="true">是</a-radio>
                            <a-radio :value="false">否</a-radio>
                        </a-radio-group>
                    </a-form-item>
                    <div class="offhandBox" v-if="formState.hasEvents">
                        <div class="formTitle">特殊效果:</div>
                        <div v-if="formState.buffs.length" class="offhandBuffsList">
                            <div class="offhandBuff df ai-c" v-for="(item, index) in formState.buffs" :key="index">
                                <span>({{ index + 1 }})</span>
                                <span>{{ item.name }} {{ item.val }}{{ item.selectDamageType ? (item.selectMultipleDamageType ? item.damageMultipleTypeText : item.damageType.name) : '' }}{{ item.unit }}</span>
                                <span v-if="item.selectColor">{{ item.color }}</span>
                                <span v-if="item.inputTime">持续{{ item.time }}回合</span>
                                <span v-if="item.inputDist">距离:{{ item.dist }}格</span>
                                <span v-if="item.switchOffhand" class="tip">可副手</span>
                                <a-switch v-if="item.switchOffhand" :checked="item.offhand" @change="changeOffhand(index)" />
                                <span v-if="item.switchOffhandonly" class="tip">仅副手生效</span>
                                <a-switch v-if="item.switchOffhandonly" :checked="item.offhandonly" @change="changeOffhandonly(index)" />
                                <div class="offhandBuffRemove fc" @click="removeOffhandBuff(index)">移除</div>
                            </div>
                        </div>
                        <div class="offhandItem df ai-c">
                            <a-select style="min-width: 20vmin;" v-model:value="offhandSelect" placeholder="请选择效果">
                                <a-select-option v-for="(item, index) in offhandBuffList" :key="index" :value="item.id">
                                    {{ item.name }}
                                </a-select-option>
                            </a-select>
                            <a-input-number style="flex: 1;" v-if="buffSelectItem && !buffSelectItem.notInput" v-model:value="offhandInput" :precision="0" :placeholder="buffSelectItem.placeholder" :min="buffSelectItem.min" :max="buffSelectItem.max" />
                            <a-input-number style="flex: 1;" v-if="buffSelectItem && buffSelectItem.inputTime" v-model:value="offhandInputTime" :precision="0" placeholder="请输入持续回合" :min="1" :max="100" />
                            <a-input-number style="flex: 1;" v-if="buffSelectItem && buffSelectItem.inputDist" v-model:value="offhandInputDist" :precision="0" placeholder="请输入距离(格)" :min="1" :max="10" />
                            <div v-if="buffSelectItem && buffSelectItem.selectColor" class="df ai-c ml"  @click="handleSelectColor">
                                请选择光照颜色<div class="button fc" :style="{ background: buffColor.value }" style="width: 10vmin;"></div>
                            </div>
                            <a-select v-if="buffSelectItem && buffSelectItem.selectDamageType && !buffSelectItem.selectMultipleDamageType" style="width: max-content;" v-model:value="damageType" placeholder="请选择伤害类型" >
                                <a-select-option v-for="(item, index) in damageTypes" :key="index" :value="item.value">
                                    {{ item.name }}
                                </a-select-option>
                            </a-select>
                            <a-select v-if="buffSelectItem && buffSelectItem.selectDamageType && buffSelectItem.selectMultipleDamageType" style="min-width: 20vmin;max-width: 30vmin;" v-model:value="damageMultipleType" placeholder="请选择伤害类型" mode="multiple" >
                                <a-select-option v-for="(item, index) in damageTypes" :key="index" :value="item.value">
                                    {{ item.name }}
                                </a-select-option>
                            </a-select>
                            <div class="button fc" @click="addBuff">添加</div>
                        </div>
                    </div>
                    <div class="mt">
                        <div class="formTitle">获取方式:</div>
                        <a-form-item label="稀有度(0~10)" name="rarity">
                            <a-input-number class="numberBox" v-model:value="formState.rarity" :precision="0" placeholder="请输入武器稀有度" :min="0" :max="10" />
                            <div class="tip">影响通过各种途径获取的概率(参考:徒手0 商人处售卖1 女神武器10)</div>
                            <div class="tip">同时也会影响售卖的价格 如需前期购买请设置为0~2</div>
                        </a-form-item>
                        <a-form-item label="是否可在商业神龛购买">
                            <a-radio-group v-model:value="formState.shop">
                                <a-radio :value="true">是</a-radio>
                                <a-radio :value="false">否</a-radio>
                            </a-radio-group>
                        </a-form-item>
                        <a-form-item label="是否在游戏开始时自动加入背包">
                            <a-radio-group v-model:value="formState.newGameInit">
                                <a-radio :value="true">是</a-radio>
                                <a-radio :value="false">否</a-radio>
                            </a-radio-group>
                        </a-form-item>
                        <a-form-item label="是否在加载游戏时自动加入背包">
                            <a-radio-group v-model:value="formState.loadInit">
                                <a-radio :value="true">是</a-radio>
                                <a-radio :value="false">否</a-radio>
                            </a-radio-group>
                        </a-form-item>
                        <a-form-item label="是否加入铁匠的商品中">
                            <a-radio-group v-model:value="formState.addBlacksmithShopItems">
                                <a-radio :value="true">是</a-radio>
                                <a-radio :value="false">否</a-radio>
                            </a-radio-group>
                        </a-form-item>
                        <a-form-item label="是否加入防具师的商品中">
                            <a-radio-group v-model:value="formState.addArmorerShopItems">
                                <a-radio :value="true">是</a-radio>
                                <a-radio :value="false">否</a-radio>
                            </a-radio-group>
                        </a-form-item>
                        <a-form-item label="是否加入制弓师的商品中">
                            <a-radio-group v-model:value="formState.addBowyerShopItems">
                                <a-radio :value="true">是</a-radio>
                                <a-radio :value="false">否</a-radio>
                            </a-radio-group>
                        </a-form-item>
                        <a-form-item label="是否加入古董商人的商品中">
                            <a-radio-group v-model:value="formState.addAntiqueShopItems">
                                <a-radio :value="true">是</a-radio>
                                <a-radio :value="false">否</a-radio>
                            </a-radio-group>
                        </a-form-item>
                        <a-form-item label="是否加入假·绑匪的商品中">
                            <a-radio-group v-model:value="formState.addShadyShopItems">
                                <a-radio :value="true">是</a-radio>
                                <a-radio :value="false">否</a-radio>
                            </a-radio-group>
                        </a-form-item>
                        <a-form-item label="可在高级启动中选择开局获得该武器">
                            <a-radio-group v-model:value="formState.statsPresets">
                                <a-radio :value="true">是</a-radio>
                                <a-radio :value="false">否</a-radio>
                            </a-radio-group>
                        </a-form-item>
                        <a-form-item v-if="formState.statsPresets" label="高级启动中该词条的点数消耗" name="statsPresetsCost">
                            <a-input-number class="numberBox" v-model:value="formState.statsPresetsCost" :precision="0" placeholder="请输入点数消耗" :min="-10" :max="10" />
                        </a-form-item>
                    </div>
                    <div class="mt">
                        <div class="formTitle">实验效果:</div>
                        <div class="tip">注意：部分效果需要工具mod才能正常工作 请在使用此mod时同时引入工具mod</div>
                        <div class="download" @click="downloadMiriruMod">下载工具mod</div>
                        <div class="miriruBuffListItem" v-for="(item, index) in miriruBuffList" :key="index">
                            <div class="buffItemTitle df ai-c mb">
                                <div class="mr df ai-c">
                                    ({{ index + 1 }}){{ item.name }}
                                    <div v-if="item.needMiriruMod" class="tip">(此效果依赖工具mod)</div>
                                </div>
                                <a-switch :checked="item.on" @change="(e: boolean) => switchMiriruBuffListOn(item.id, e)" />
                            </div>
                            <div v-if="item.on" class="df ai-c">
                                <div class="buffItemTitle mr">触发概率:</div>
                                <a-input-number style="flex: 1;" :value="item.change" :precision="0" placeholder="请输入触发概率(%)" :min="1" :max="100" @change="(e: any) => handleMiriruBuffInput(e, item.id, 'change')" />
                            </div>
                            <div v-if="item.on && item.inputBinder" class="df ai-c mt">
                                <div class="buffItemTitle mr">被束缚时提示:</div>
                                <a-input :value="item.addSelfRestraintTip" placeholder="请输入被束缚时提示 [RESTRAINTNAME]为拘束名称" @change="(e: any) => handleMiriruBuffInput(e.target.value, item.id, 'addSelfRestraintTip')" />
                            </div>
                            <div v-if="item.on && item.inputBinder" class="df ai-c mt">
                                <div class="buffItemTitle mr">束缚紧度:</div>
                                <a-select style="flex: 1;" :value="item.power" placeholder="请选择束缚紧度" @change="(e: any) => handleMiriruBuffInput(e, item.id, 'power')">
                                    <a-select-option :value="0">宽松</a-select-option>
                                    <a-select-option :value="1">正常(根据当前楼层决定 后期会超过非常紧)</a-select-option>
                                    <a-select-option :value="10">紧</a-select-option>
                                    <a-select-option :value="20">非常紧</a-select-option>
                                </a-select>
                            </div>
                            <div v-if="item.on && item.inputBinder" class="mt df ai-c">
                                <div class="buffItemTitle mr">是否指定拘束类型(如不指定则随机生成):</div>
                                <a-switch :checked="item.atkAddSelfRestraintAssignBindType" @change="(e: boolean) => handleMiriruBuffInput(e, item.id, 'atkAddSelfRestraintAssignBindType')" />
                            </div>
                            <div v-if="item.on && item.inputBinder && item.atkAddSelfRestraintAssignBindType">
                                <div class="buffItemTitle mr">指定拘束词条(请尽可能多选，少量的词条可能会无法生成拘束)</div>
                                <a-select
                                    :value="item.restraintAssignBindTags"
                                    :filter-option="filterOption"
                                    mode="multiple"
                                    style="width: 100%"
                                    placeholder="请选择拘束词条"
                                    :options="RestraintTagTypes"
                                    @change="(e: any) => handleMiriruBuffInput(e, item.id, 'restraintAssignBindTags')"
                                ></a-select>
                            </div>
                            <div v-if="item.on && item.inputBinder" class="mt df ai-c">
                                <div class="buffItemTitle mr">是否覆盖拘束自带的锁:</div>
                                <a-switch :checked="item.isLock" @change="(e: boolean) => handleMiriruBuffInput(e, item.id, 'isLock')" />
                            </div>
                            <div v-if="item.on && item.inputBinder && item.isLock" class="df ai-c mt">
                                <div class="buffItemTitle mr">锁类型:</div>
                                <a-select stye="flex: 1;"l :value="item.lockType" placeholder="请选择锁类型" @change="(e: any) => handleMiriruBuffInput(e, item.id, 'lockType')">
                                    <a-select-option v-for="(lock, lockIndex) in kdAllLockList" :key="lockIndex" :value="lock.value">{{ lock.label }}</a-select-option>
                                </a-select>
                            </div>
                            <div class="mt df ai-c" v-if="item.on && item.inputVal">
                                <div class="buffItemTitle"></div>
                                <a-input-number style="flex: 1;" :value="item.val" :precision="0" :placeholder="item.placeholder" 
                                :min="item.minValue || 1" :max="item.maxValue || 100" @change="(e: any) => handleMiriruBuffInput(e, item.id, 'val')" />
                            </div>
                            <div class="mt df ai-c" v-if="item.on && item.selectDamageType">
                                <div class="buffItemTitle mr">伤害类型:</div>
                                <a-select style="flex: 1;" :value="item.damageType" placeholder="请选择伤害类型" 
                                @change="(e: any) => handleMiriruBuffInput(e, item.id, 'damageType')">
                                    <a-select-option v-for="(item, index) in KinkyDungeonWeaponsTypeList" :key="index" :value="item.id">
                                        {{ item.name }}
                                    </a-select-option>
                                </a-select>
                            </div>
                            <div class="mt df ai-c" v-if="item.on && item.selectDresses">
                                <div class="buffItemTitle mr">服装:</div>
                                <a-select style="flex: 1;" :value="item.dresses" placeholder="请选择伤害类型" 
                                @change="(e: any) => handleMiriruBuffInput(e, item.id, 'dresses')">
                                    <a-select-option v-for="(item, index) in kdDressesList" :key="index" :value="item.id">
                                        {{ item.name }}
                                    </a-select-option>
                                </a-select>
                            </div>
                        </div>
                    </div>
                </a-form>
                <view v-if="!showOtherMod" class="buttonList">
                    <div class="button fc" @click="saveSingleWeapon">{{ targetCreateNewWeapon ? '创建新武器' : '保存' }}</div>
                    <div class="button fc" @click="exportSingleWeaponMod">导出单武器mod</div>
                </view>
            </div>
        </div>
        <div class="kdWeaponCreate" v-show="hasCreateSpell">
            <div class="title">Kinky Dungeon 自定义法术</div>
            <div class="form">
                <SpellFrom ref="SpellFromRef" :create="targetCreateNewSpell" :modList="showList" :targetEditModIndex="targetEditModIndex" :targetEditSpellIndex="targetEditSpellIndex" :showOtherMod="showOtherMod" @pushModListSpell="pushModListSpell" @editModListSpell="editModListSpell"></SpellFrom>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import {
    KinkyDungeonWeapons,
    KinkyDungeonWeaponsList,
    KinkyDungeonWeaponsType,
    KinkyDungeonWeaponsTypeObj,
    KinkyDungeonWeaponsTypeList,
    KinkyDungeonWeaponsSfx,
    KinkyDungeonWeaponsSfxObj,
    KinkyDungeonWeaponsSfxList,
    KinkyDungeonWeaponsTags,
    KinkyDungeonWeaponsTagsObj,
    KinkyDungeonWeaponsTagsList,
    KinkyDungeonWeaponsKeys,
    bindTypeList,
    RestraintTagTypes,
    kdAllLockList,
    kdDressesList,
} from "../utils/kd.js";
import { isDev } from '@/utils/env.js';
import { message } from 'ant-design-vue';
import { ref, reactive, toRaw, onMounted, computed, createVNode, h } from "vue"
import type { UnwrapRef } from 'vue';
import { exportWeaponModFile, saveMod, editMod, loadModList, deleteMod, deleteModWeapon, deleteModSpell, initWeaponFormState, saveWeaponAtMod, resetOldSave, importWeaponModFile, importSaveMod, initMiriruBuffList, formatImportWeaponsData, handleShowTip } from '@/utils/utils';
import type { UploadProps } from 'ant-design-vue';
import type { Rule } from 'ant-design-vue/es/form';
import { PlusOutlined, LoadingOutlined, ExclamationCircleOutlined, QuestionCircleOutlined } from '@ant-design/icons-vue';
import { colorEvent } from 'v3-color-picker';
import { Modal } from 'ant-design-vue';
import dayjs from 'dayjs'
import fetch from "../api/fetch.js"
import { uploadMod } from "../api/upload.js"
import { spellTemplateList } from "../utils/kdSpell.js"
import SpellFrom from "@/components/spellFrom.vue"
import _ from "lodash"
const filterOption = (input: string, option: any) => {
    console.log('option input res', input, option, option.value.indexOf(input) != -1 ? true : false)
    return option.label.indexOf(input) != -1 ? true : false
}

// 引入所有武器图片
// 导入@/assets/weaponImg下的所有文件
const weaponImgs = import.meta.glob("@/assets/weaponImg/*")
const weaponImgListKeys = Object.keys(weaponImgs);
// 当前环境是否为生产环境
let isProduction = process.env.NODE_ENV === 'production'
const weaponImgList = weaponImgListKeys.map((item) => {
    let name = item.replace('/src/assets/weaponImg/', '').replace('.png', '')
    return {
        img: isProduction ? '/assets/' + name + '.png' : item,
        name,
    }
})
console.log('weaponImgList',weaponImgList)
const formRef = ref();
const createFormRef = ref();
const createSpellFormRef = ref();
const editFormRef = ref();
const SpellFromRef = ref();
const uploadLoading = ref(false);
const handleUpload: UploadProps['customRequest'] = async (options) => {
    const reader = new FileReader();
    reader.readAsDataURL(options.file as any);
    reader.onload = () => {
        formState.img = reader.result as string;
        console.log('formState.img',formState.img)
    }
};
interface FormState {
    img?: string;
    newGameInit: boolean;
    loadInit: boolean;
    hasStam50mult: boolean;
    ignite: boolean; // 点燃目标 与可范围攻击互斥
    isRange: boolean; // 可范围攻击 与点燃目标互斥
    range?: number;
    hasEvents?: boolean; // 是否有特殊效果
    buffs: any[]; // 效果
    miriruBuffs: any[]; // 实验效果 非kd自带
    enName?: string,
    znName?: string,
    desc?: string,
    desc2?: string,
    atkDesc?: string,
    damage?: number | null,
    chance?: number | null,
    type?: string | null,
    rarity?: number | null,
    shop?: boolean,
    sfx?: string | null,
    tags?: string[]
    staminacost?: number | null,
    clumsy?: boolean,
    heavy?: boolean,
    light?: boolean,
    nocrit?: boolean,
    crit?: number | null,
    stam50mult?: number | null,
    cutBonus?: number,
    magic?: boolean,
    addBind?: boolean,
    bind?: number,
    bindType?: string | null,
    bindEff?: number | null,
    noDamagePenalty?: boolean,
    noHands?: boolean,
    novulnerable?: boolean,
    bindcrit?: number | null,
    addAntiqueShopItems: boolean, // 是否加入古董商人的商品中
    addBlacksmithShopItems?: boolean, // 是否加入铁匠的商品中
    addArmorerShopItems?: boolean, // 是否加入防具师的商品中
    addBowyerShopItems?: boolean, // 是否加入制弓师的商品中
    addShadyShopItems?: boolean, // 是否加入假·绑匪的商品中
    statsPresets?: boolean, // 是否可在高级启动中选择开局获得该武器
    statsPresetsCost?: number, // 高级启动中 该词条的点数消耗
}
interface offhandBuff {
    name: string,
    id: string,
    placeholder?: string,
    min?: number,
    max?: number,
    switchOffhand?: boolean,
    switchOffhandonly?: boolean,
    selectColor?: boolean,
    color?: string,
    notInput?: boolean,
    selectDamageType?: boolean,
    selectMultipleDamageType?: boolean,
    inputTime?: boolean,
    inputDist?: boolean,
}
interface CreateFormState {
    name?: string,
    desc?: string,
    author?: string,
}
interface CreateSpellFormState {
    type?: string | null,
}
const formState: UnwrapRef<FormState> = reactive(initWeaponFormState())
const createFormState : UnwrapRef<CreateFormState> = reactive({
    name: '',
    desc: '',
    author: '',
})
const createSpellFormState : UnwrapRef<CreateSpellFormState> = reactive({
    type: null,
})
const rules: Record<string, Rule[]> = {
    znName: [{ required: true, message: '请输入武器名称', trigger: 'change' }],
    enName: [{ required: true, message: '请输入英文名称', trigger: 'change' }],
    desc: [{ required: true, message: '请输入武器描述', trigger: 'change' }],
    desc2: [{ required: true, message: '请输入武器性能描述', trigger: 'change' }],
    atkDesc: [{ required: true, message: '请输入攻击描述', trigger: 'change' }],
    damage: [{ required: true, message: '请输入伤害', trigger: 'change' }],
    chance: [{ required: true, message: '请输入命中率', trigger: 'change' }],
    type: [{ required: true, message: '请选择伤害类型', trigger: 'change' }],
    rarity: [{ required: true, message: '请输入稀有度', trigger: 'change' }],
    sfx: [{ required: true, message: '请选择武器音效', trigger: 'change' }],
    tags: [{ required: true, message: '请选择武器词条', trigger: 'change' }],
    staminacost: [{ required: true, message: '请输入体力消耗', trigger: 'change' }],
    crit: [{ required: true, message: '请输入暴击伤害', trigger: 'change' }],
    stam50mult: [{ required: true, message: '请输入耐力消耗倍率', trigger: 'change' }],
    bind: [{ required: true, message: '请输入束缚值', trigger: 'change' }],
    bindType: [{ required: true, message: '请选择束缚类型', trigger: 'change' }],
    bindEff: [{ required: true, message: '请输入束缚效率', trigger: 'change' }],
    bindcrit: [{ required: true, message: '请输入束缚暴击倍率', trigger: 'change' }],
    range: [{ required: true, message: '请输入攻击范围', trigger: 'change' }],
    statsPresetsCost: [{ required: true, message: '请输入消耗点数', trigger: 'change' }],
}
const rules1: Record<string, Rule[]> = {
    name: [{ required: true, message: '请输入mod名称', trigger: 'change' }],
    desc: [{ required: true, message: '请输入mod描述', trigger: 'change' }],
    author: [{ required: true, message: '请输入作者', trigger: 'change' }],
}
const wrapperCol = { style: { width: '20vmin' } };

console.log('KinkyDungeonWeaponsKeys',KinkyDungeonWeaponsKeys)
let damageTypes = [
    { name: '火焰', value: 'fire' },
    { name: '冰霜', value: 'ice' },
    { name: '皂化', value: 'soap' },
    { name: '斩击', value: 'slash' },
    { name: '穿刺', value: 'pierce' },
    { name: '徒手', value: 'unarmed' },
    { name: '疼痛', value: 'pain' },
    { name: '暗影', value: 'cold' },
    { name: '粘液', value: 'glue' },
    { name: '锁链', value: 'chain' },
    { name: '挠痒', value: 'tickle' },
    { name: '碾压', value: 'crush' },
    { name: '电击', value: 'electric' },
    { name: '灵魂', value: 'soul' },
    { name: '魅惑', value: 'charm' },
]

const modList = ref([] as any[]) // 本地mod列表
const otherModList = ref([] as any[]) // 社区mod列表
const reviewModList = ref([] as any[]) // 待审核mod列表
const targetEditModIndex = ref(-1) // 当前正在编辑的mod的index
const targetCreateNewWeapon = ref(false) // 当前是否在创建新武器(判断创建武器或编辑武器)
const targetEditWeaponIndex = ref(-1) // 当前正在编辑的武器的index
const hasCreateWeapon = ref(false) // 显示自定义武器界面
const targetCreateNewSpell = ref(false) // 当前是否在创建新法术(判断创建法术或编辑法术)
const targetEditSpellIndex = ref(-1) // 当前正在编辑的法术的index
const hasCreateSpell = ref(false) // 显示自定义法术界面
const activeKey = ref([])
const offhandSelect = ref(null)
const offhandBuffList = [ // kd自带特殊效果
    { id: 'blockBuff', name: '格挡加成(可副手)', placeholder: '请输入格挡加成(小刀10 盾牌60)', min: 1, max: 1000, switchOffhand: false, switchOffhandonly: true },
    { id: 'buffMagicCrit', name: '魔法暴击加成(%)', placeholder: '请输入魔法暴击加成(附魔刀20%)', min: 1, max: 1000, unit: '%', switchOffhand: true, switchOffhandonly: true },
    { id: 'buffWeaponCrit', name: '暴击加成(%)', placeholder: '请输入暴击加成(匕首10%)', min: 1, max: 1000, unit: '%', switchOffhand: true, switchOffhandonly: true },
    { id: 'armorBuff', name: '物理防御加成', placeholder: '请输入物理防御加成(塔盾30)', min: 1, max: 1000, switchOffhand: true, switchOffhandonly: true },
    { id: 'spellWardBuff', name: '魔法防御加成', placeholder: '请输入魔法防御加成(魔法盾牌20)', min: 1, max: 1000, switchOffhand: true, switchOffhandonly: true },
    { id: 'WeaponLight', name: '照明效果', placeholder: '请输入照明范围(火焰剑5格 寒冰剑3格)', min: 1, max: 10, selectColor: true, unit: '格', switchOffhand: true, switchOffhandonly: true },
    { id: 'Float', name: '绘制立绘时武器悬浮', notInput: true, },
    { id: 'playerAttackStun', name: '攻击时眩晕目标', placeholder: '请输入眩晕回合(盾牌4 塔盾7)', min: 1, max: 100, unit: '回合' },
    { id: 'playerAttackDamage', name: '攻击附加伤害', placeholder: '请输入附加伤害', min: 1, max: 1000, switchOffhand: true, switchOffhandonly: true, selectDamageType: true, unit: '伤害' },
    { id: 'ChangeDamageVulnerable', name: '对脆弱目标附加伤害', placeholder: '请输入附加伤害', min: 1, max: 1000, switchOffhand: true, switchOffhandonly: true, selectDamageType: true, unit: '伤害' },
    { id: 'ChangeDamageUnaware', name: '对未察觉目标附加伤害', placeholder: '请输入附加伤害', min: 1, max: 1000, switchOffhand: true, switchOffhandonly: true, selectDamageType: true, unit: '伤害' },
    { id: 'Cleave', name: '同时对旁边的敌人造成伤害', placeholder: '请输入伤害值', min: 1, max: 1000, selectDamageType: true, unit: '伤害' },
    { id: 'Cleave1', name: '同时对旁边的敌人造成持续伤害', placeholder: '请输入伤害值', min: 1, max: 1000, selectDamageType: true, unit: '伤害', inputTime: true },
    { id: 'Knockback', name: '击退', placeholder: '请输入击退距离(格)', min: 1, max: 10, unit: '格' },
    { id: 'Buff', name: '伤害提升', placeholder: '请输入伤害提升比例(%)', min: 1, max: 1000, unit: '伤害(%)', switchOffhand: true, switchOffhandonly: true, selectDamageType: true },
    { id: 'BuffMulti', name: '多属性伤害提升', placeholder: '请输入伤害提升比例(%)', min: 1, max: 1000, unit: '伤害(%)', switchOffhand: true, switchOffhandonly: true, selectDamageType: true, selectMultipleDamageType: true },
    { id: 'Pierce', name: '穿透(对后方敌人造成伤害)', placeholder: '请输入伤害值', min: 1, max: 1000, selectDamageType: true, unit: '伤害', inputDist: true },
    { id: 'ApplyToy', name: '添加玩具', notInput: true, switchOffhand: true, switchOffhandonly: true, },
    { id: 'ActivateVibration', name: '激活震动玩具', placeholder: '请输入震动强度(1-5)', min: 1, max: 10, switchOffhand: true, switchOffhandonly: true, inputTime: true, unit: '强度' },
] as offhandBuff[]
const offhandInput = ref('')
const offhandInputTime = ref(null)
const offhandInputDist = ref(null)
const showSelectImage = ref(false)
const showCreateMod = ref(false)
const showOtherMod = ref(false) // 显示社区mod
const showReviewMod = ref(false) // 显示社区mod(待审核)
const showEditModInfo = ref(false)
const showCreateSpell = ref(false)
const hasEditModInfoIndex = ref(-1)
const modListLoading = ref(false)
const showList = computed(() => {
    if (showOtherMod.value) {
        return showReviewMod.value ? reviewModList.value : otherModList.value
    }
    else return modList.value
})
const buffColor = ref({
    value: '#000',
    btn: true,
    theme: "light"
})
const damageType = ref(null)
const damageMultipleType = ref([])
const buffSelectItem = computed(() => {
    if (offhandSelect.value) {
        let index = offhandBuffList.findIndex((v) => v.id == offhandSelect.value)
        if (index != -1) return offhandBuffList[index]
        else return null
    }
    else return null
})
const addBuff = () => {
    let id = buffSelectItem.value?.id
    let val = offhandInput.value
    let item = buffSelectItem.value as any
    console.log('addBuff item', item)
    if (id) {
        let has = formState.buffs.find((v) => v.id == id)
        if (has) {
            return message.error('已添加同类效果，请删除对应效果后重新添加')
        }
        if (val || item.notInput) {
            let params = { id, val, name: item.name, offhandonly: false, offhand: false, switchOffhand: item.switchOffhand, switchOffhandonly: item.switchOffhandonly, unit: item.unit, selectColor: item.selectColor, color: item.selectColor ? buffColor.value.value : null, times: 3, selectDamageType: item.selectDamageType, selectMultipleDamageType: item.selectMultipleDamageType, time: item.inputTime ? offhandInputTime.value : null, inputTime: item.inputTime, dist: item.inputDist ? offhandInputDist.value : null, inputDist: item.inputDist } as any
            if (item.selectDamageType) {
                if (item.selectMultipleDamageType) {
                    params.damageMultipleType = damageMultipleType.value.map((v: any) => damageTypes.find((j: any) => j.value == v))
                    params.damageMultipleTypeText = params.damageMultipleType.map((v: any) => v?.name).join('、')
                }
                else params.damageType = damageTypes.find((v) => v.value == damageType.value)
            }
            formState.buffs.push(params)
            offhandSelect.value = null
            offhandInput.value = ''
            offhandInputTime.value = null
            offhandInputDist.value = null
            buffColor.value.value = '#000'
            damageType.value = null
            damageMultipleType.value = []
            message.success('添加成功')
            console.log('buffs',formState.buffs)
        }
        else message.error(buffSelectItem.value?.placeholder || '请输入副手效果值')
    }
    else message.error('请选择副手效果')
}
const removeOffhandBuff = (index: number) => {
    formState.buffs.splice(index, 1)
}
const changeOffhandonly = (index: number) => {
    formState.buffs[index].offhandonly = !formState.buffs[index].offhandonly
}
const changeOffhand = (index: number) => {
    formState.buffs[index].offhand = !formState.buffs[index].offhand
}

// 实验效果
const miriruBuffList = ref(initMiriruBuffList()) as any
// 同步miriruBuffList到formState.miriruBuffs
const changeMiriruBuff = (type: string, formStateMiriruBuffsId: string, index: number) => {
    miriruBuffList.value[index] = initMiriruBuffList()[index] // 重置miriruBuffList
    miriruBuffList.value[index].on = type == 'add' ? true : false
    if (type == 'add') {
        let id = miriruBuffList.value[index].id
        let params = { id } as any
        params.change = null
        params.addEvent = miriruBuffList.value[index]?.addEvent || false
        if (id == 'atkAddSelfRestraint' || id == 'castAddSelfRestraint') {
            params.addSelfRestraintTip = '你的行为已被注意到，你突然发现自己穿着[RESTRAINTNAME]！'
            params.power = null
            params.atkAddSelfRestraintAssignBindType = false
            params.restraintAssignBindTags = []
            params.isLock = false
            params.lockType = ''
        }
        if (miriruBuffList.value[index].inputVal) {
            params.inputVal = true
            params.val = null
            params.placeholder = miriruBuffList.value[index].placeholder
        }
        if (miriruBuffList.value[index].selectDamageType) {
            params.selectDamageType = true
            params.damageType = null
        }
        if (miriruBuffList.value[index].selectDresses) {
            params.selectDresses = true
            params.dresses = null
        }
        formState.miriruBuffs.push(params)
        console.log('添加实验效果 formState.miriruBuffs miriruBuffList.value',formState.miriruBuffs, miriruBuffList.value)
    }
    if (type == 'remove') {
        let formStateMiriruBuffsIndex = formState.miriruBuffs.findIndex((v: any) => v.id == formStateMiriruBuffsId)
        if (formStateMiriruBuffsIndex == -1) return
        formState.miriruBuffs.splice(formStateMiriruBuffsIndex, 1)
    }
}
const inputMiriruBuff = (val: any, id: string, key: string) => {
    let index = formState.miriruBuffs.findIndex((v: any) => v.id == id)
    if (index != -1) formState.miriruBuffs[index][key] = val
    console.log('修改实验效果 formState.miriruBuffs',formState.miriruBuffs)
    let index1 = miriruBuffList.value.findIndex((v: any) => v.id == id)
    if (index1 != -1) miriruBuffList.value[index1][key] = val
}
const handleMiriruBuffInput = (e: any, id: string, key: string) => {
    // console.log('handleMiriruBuffInput',e, id, key)
    inputMiriruBuff(e, id, key)
}
const switchMiriruBuffListOn = (id: string, e: boolean) => {
    let index = miriruBuffList.value.findIndex((v: any) => v.id == id)
    if (index == -1) return
    miriruBuffList.value[index].on = e
    changeMiriruBuff(e ? 'add' : 'remove', id, index)
}

const handleSelectColor = (e: any) => {
    colorEvent(e, buffColor.value as any)
    e.preventDefault();
}
const selectImage = (item: any) => {
    console.log('selectImage',item)
    // 读取本地图片(如/src/assets/weaponImg/Bola.png) 并转化为base64
    let img = new Image()
    img.src = item.img
    img.onload = () => {
        let canvas = document.createElement('canvas')
        canvas.width = img.width
        canvas.height = img.height
        let ctx = canvas.getContext('2d')
        ctx?.drawImage(img, 0, 0, img.width, img.height)
        let dataURL = canvas.toDataURL('image/png')
        formState.img = dataURL
        showSelectImage.value = false
    }
}

// 校验
const validate = () => {
    return new Promise((resolve, reject) => {
        formRef.value
        .validate()
        .then(() => {
            if (formState.img == '') {
                message.error('请上传武器图片')
                reject('请上传武器图片')
            }
            if (formState.hasEvents && formState.buffs.length == 0) {
                message.error('请添加武器效果')
                reject('请添加武器效果')
            }
            if (formState.miriruBuffs && formState.miriruBuffs.length) {
                console.log('validate formState.miriruBuffs',formState.miriruBuffs)
                formState.miriruBuffs.map(i => {
                    if (i.change == null) {
                        message.error('请输入触发概率')
                        reject('请输入触发概率')
                    }
                    else if (i.id == 'atkAddSelfRestraint' || i.id == 'castAddSelfRestraint') {
                        if (i.addSelfRestraintTip == null) {
                            message.error('请输入被束缚时提示')
                            reject('请输入被束缚时提示')
                        }
                        // 不包含[RESTRAINTNAME]
                        else if (i.addSelfRestraintTip.indexOf('[RESTRAINTNAME]') == -1) {
                            message.error('被束缚时提示中必须包含[RESTRAINTNAME]')
                            reject('被束缚时提示中必须包含[RESTRAINTNAME]')
                        }
                        else if (i.power == null) {
                            message.error('请选择束缚紧度')
                            reject('请选择束缚紧度')
                        }
                        else if (i.atkAddSelfRestraintAssignBindType && i.restraintAssignBindTags.length == 0) {
                            message.error('请选择拘束词条')
                            reject('请选择拘束词条')
                        }
                        else if (i.isLock && i.lockType == null) {
                            message.error('请选择锁类型')
                            reject('请选择锁类型')
                        }
                    }
                    else if (i.inputVal && !i.val) {
                        message.error(i.placeholder)
                        reject(i.placeholder)
                    }
                    else if (i.selectDamageType && !i.damageType) {
                        message.error('请选择伤害类型')
                        reject('请选择伤害类型')
                    }
                    else if (i.selectDresses && !i.dresses) {
                        message.error('请选择服装')
                        reject('请选择服装')
                    }
                })
            }
            resolve(true)
        })
        .catch((err: any) => {
            console.log('校验失败', err)
            reject()
        })
    })
}

// 保存武器到当前编辑的mod
const saveSingleWeapon = () => {
    validate()
    .then(() => {
        let data = JSON.parse(JSON.stringify(formState))
        if (targetCreateNewWeapon.value) {
            // 创建新武器
            console.log('创建新武器 modList.value targetEditModIndex modList.value[targetEditModIndex.value]', modList.value, targetEditModIndex.value, modList.value[targetEditModIndex.value])
            let hasName = modList.value[targetEditModIndex.value].mod.weapons.find((v: any) => v.znName == data.znName)
            // 存在同名武器
            if (hasName) return message.error('存在同名武器，请修改武器名称')
            modList.value[targetEditModIndex.value].mod.weapons.push({ ...data })
            saveWeaponAtMod(data, modList.value[targetEditModIndex.value].mod.name, true)
            message.success('添加成功')
        }
        else {
            // 编辑武器
            modList.value[targetEditModIndex.value].mod.weapons[targetEditWeaponIndex.value] = { ...data }
            // weapon属性 mod名字 当前在编辑武器
            saveWeaponAtMod(data, modList.value[targetEditModIndex.value].mod.name, false)
            message.success('编辑成功')
            console.log('保存武器 formState', data)
        }
    })
    .catch((err) => {
        console.log('saveSingleWeapon err', err)
    })
}

const formatWeaponInfo = (result: any) => {
    result.damage = result.damage / 10
    result.chance = result.chance / 100
    result.staminacost = result.staminacost / 10
    result.crit = result.crit / 100
    if (result.hasStam50mult) result.stam50mult = result.stam50mult / 100
    else delete result.stam50mult
    delete result.hasStam50mult
    if (result.cutBonus) result.cutBonus = result.cutBonus / 100
    else delete result.cutBonus
    if (!result.heavy) delete result.heavy
    if (!result.clumsy) delete result.clumsy
    if (!result.light) delete result.light
    if (!result.nocrit) delete result.nocrit
    if (!result.magic) delete result.magic
    if (!result.addBind) {
        delete result.addBind
        delete result.bind
        delete result.bindType
        delete result.bindEff
        delete result.bindcrit
    }
    else {
        result.bind = result.bind / 10
        result.bindEff = result.bindEff / 100
        result.bindcrit = result.bindcrit / 100
    }
    if (!result.noDamagePenalty) delete result.noDamagePenalty
    if (!result.noHands) delete result.noHands
    if (!result.novulnerable) delete result.novulnerable
    if (result.ignite) result.special = { type: "ignite" } // 点燃目标
    delete result.ignite
    if (result.isRange) result.special = { type: "attack", range: result.range + 0.99 }
    delete result.isRange
    delete result.range
    if (result.hasEvents && result.buffs && result.buffs.length) {
        result.events = []
        console.log('result.buffs',result.buffs)
        result.buffs.map((item: any) => {
            if (item.id == 'blockBuff') {
                let p = {
                    type: "blockBuff",
                    trigger: "tick",
                    offhand: true,
                    offhandonly: item.offhandonly,
                    power: item.val / 100
                }
                if (item.offhandonly) p.offhandonly = true
                result.events.push(p)
            }
            if (item.id == 'buffMagicCrit') {
                let p = {
                    type: "buffMagicCrit",
                    trigger: "calcCrit",
                    power: item.val / 100
                } as any
                if (item.offhand) p.offhand = true
                if (item.offhandonly) p.offhandonly = true
                result.events.push(p)
            }
            if (item.id == 'buffWeaponCrit') {
                let p = {
                    type: "buffWeaponCrit",
                    trigger: "calcCrit",
                    power: item.val / 100
                } as any
                if (item.offhand) p.offhand = true
                if (item.offhandonly) p.offhandonly = true
                result.events.push(p)
            }
            if (item.id == 'armorBuff') {
                let p = {
                    type: "armorBuff",
                    trigger: "tick",
                    power: item.val / 10
                } as any
                if (item.offhand) p.offhand = true
                if (item.offhandonly) p.offhandonly = true
                result.events.push(p)
            }
            if (item.id == 'spellWardBuff') {
                let p = {
                    type: "spellWardBuff",
                    trigger: "tick",
                    power: item.val / 10
                } as any
                if (item.offhand) p.offhand = true
                if (item.offhandonly) p.offhandonly = true
                result.events.push(p)
            }
            if (item.id == 'WeaponLight') {
                let p = {
                    type: "WeaponLight",
                    trigger: "getLights",
                    power: item.val,
                    color: item.color
                } as any
                if (item.offhand) p.offhand = true
                if (item.offhandonly) p.offhandonly = true
                result.events.push(p)
            }
            if (item.id == 'Float') {
                result.events.push({
                    type: "Float",
                    trigger: "draw",
                })
            }
            if (item.id == 'playerAttackStun') {
                let p = {
                    type: "ElementalEffect",
                    trigger: "playerAttack",
                    damage: "stun", // 击晕效果
                    power: 0, 
                    time: item.val
                } as any
                result.events.push(p)
            }
            if (item.id == 'playerAttackDamage') {
                let p = {
                    type: "ElementalEffect",
                    trigger: "playerAttack",
                    power: item.val / 10, 
                    damage: item.damageType.value
                } as any
                if (item.offhand) p.offhand = true
                if (item.offhandonly) p.offhandonly = true
                result.events.push(p)
            }
            if (item.id == 'ChangeDamageVulnerable') {
                let p = {
                    type: "ChangeDamageVulnerable",
                    trigger: "beforePlayerAttack",
                    power: item.val / 10, 
                    damage: item.damageType.value
                } as any
                if (item.offhand) p.offhand = true
                if (item.offhandonly) p.offhandonly = true
                result.events.push(p)
            }
            if (item.id == 'ChangeDamageUnaware') {
                let p = {
                    type: "ChangeDamageUnaware",
                    trigger: "beforePlayerAttack",
                    power: item.val / 10, 
                    damage: item.damageType.value
                } as any
                if (item.offhand) p.offhand = true
                if (item.offhandonly) p.offhandonly = true
                result.events.push(p)
            }
            if (item.id == 'Cleave') {
                let p = {
                    type: "Cleave",
                    trigger: "playerAttack",
                    power: item.val / 10, 
                    damage: item.damageType.value
                } as any
                result.events.push(p)
            }
            if (item.id == 'Cleave1') {
                let p = {
                    type: "Cleave",
                    trigger: "playerAttack",
                    power: item.val / 10, 
                    damage: item.damageType.value,
                    time: item.time
                } as any
                result.events.push(p)
            }
            if (item.id == 'Knockback') {
                let p = {
                    type: "Knockback",
                    trigger: "playerAttack",
                    dist: item.val
                } as any
                result.events.push(p)
            }
            if (item.id == 'Buff') {
                let p = {
                    type: "Buff",
                    trigger: "tick",
                    power: item.val / 100,
                    buffType: item.damageType.value + 'DamageBuff',
                } as any
                if (item.offhand) p.offhand = true
                if (item.offhandonly) p.offhandonly = true
                result.events.push(p)
            }
            if (item.id == 'BuffMulti') {
                let buffTypes = item.damageMultipleType.map((item: any) => {
                    return item.value + 'DamageBuff'
                })
                let p = {
                    type: "BuffMulti",
                    trigger: "tick",
                    power: item.val / 100,
                    buffTypes
                } as any
                if (item.offhand) p.offhand = true
                if (item.offhandonly) p.offhandonly = true
                result.events.push(p)
            }
            if (item.id == 'Pierce') {
                let p = {
                    type: "Pierce",
                    trigger: "playerAttack",
                    power: item.val / 10,
                    damage: item.damageType.value,
                    dist: item.dist
                } as any
                result.events.push(p)
            }
            if (item.id == 'ApplyToy') {
                let p = {
                    trigger: "playerAttack", // 攻击时触发
                    duration: 40, // 效果持续40回合
                } as any
                if (item.offhand) p.offhand = true
                if (item.offhandonly) p.offhandonly = true
                result.events.push(p)
            }
            if (item.id == 'ActivateVibration') {
                let p = {
                    type: "ActivateVibration", // 事件类型：激活震动
                    trigger: "playerAttack", // 攻击时触发
                    power: item.val, // 震动强度1
                    time: item.time // 持续15回合
                } as any
                if (item.offhand) p.offhand = true
                if (item.offhandonly) p.offhandonly = true
                result.events.push(p)
            }
        })
    }
    delete result.range
    delete result.isRange
    delete result.time
    // 特殊效果 等完善
    delete result.hasEvents
    console.log('result',result)
    return result
}

// 导出单武器mod
const exportSingleWeaponMod = () => {
    validate()
    .then(() => {
        let result = { ...formState } as any
        result = formatWeaponInfo(result)
        exportWeaponModFile({
            mod: {
                author: 'miriru mod creator(kd自定义mod)',
                desc: '自定义武器mod',
                name: result.znName,
                weapons: [result],
                spell: [],
            },
            ver: '1.0.0',
            createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
            updateTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        }, true)
        .then(() => {
            console.log('exportSingleWeaponMod 导出成功')
            message.success('导出成功喵~')
        })
        .catch((err: any) => {
            console.log('exportSingleWeaponMod 导出失败',err)
            message.error('导出失败喵~')
        })
    })
}

// 导出mod
const exportMod = (index: number) => {
    let modItem = JSON.parse(JSON.stringify(showList.value[index]))
    modItem.mod.weapons = modItem.mod.weapons.map((item: any) => {
        return formatWeaponInfo(item)
    })
    exportWeaponModFile(modItem)
    .then(() => {
        console.log('exportMod 导出成功')
        message.success('导出成功喵~')
    })
    .catch((err: any) => {
        console.log('exportMod 导出失败',err)
        message.error('导出失败喵~')
    })
}

const createMod = () => {
    // 创建mod
    let params = {
        name: createFormState.name,
        desc: createFormState.desc,
        author: createFormState.author,
        weapons: [],
        spell: [],
    }
    createFormRef.value
    .validate()
    .then(() => {
        console.log('createMod params',params)
        let { result, success, msg } = saveMod(params, true)
        showCreateMod.value = false
        createFormState.author = ''
        createFormState.name = ''
        createFormState.desc = ''
        if (success) {
            modList.value.push(result)
            message.success('创建成功喵~')
        }
        else {
            message.error(msg)
        }
    })
}

const handleShowEditModInfo = (index: number) => {
    createFormState.author = modList.value[index].mod.author
    createFormState.name = modList.value[index].mod.name
    createFormState.desc = modList.value[index].mod.desc
    showEditModInfo.value = true
    hasEditModInfoIndex.value = index
}

// 编辑mod信息
const editModInfo = () => {
    editFormRef.value
    .validate()
    .then(() => {
        showEditModInfo.value = false
        let result = editMod(createFormState.author, createFormState.name, createFormState.desc, hasEditModInfoIndex.value)
        createFormState.author = ''
        createFormState.name = ''
        createFormState.desc = ''
        modList.value = result
        message.success('创建成功喵~')
    })
}

// 删除本地mod
const handleDeleteMod = (index: number) => {
    Modal.confirm({
        title: '提示',
        icon: createVNode(ExclamationCircleOutlined),
        content: '确认删除此mod?',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
            deleteMod(modList.value[index].mod.name)
            modList.value.splice(index, 1)
            message.success('删除成功')
            hasCreateWeapon.value = false
            hasCreateSpell.value = false
        },
    })
}

// 删除本地武器
const handleDeleteWeapon = (modIndex: number, weaponIndex: number) => {
    Modal.confirm({
        title: '提示',
        icon: createVNode(ExclamationCircleOutlined),
        content: '确认删除武器: ' + modList.value[modIndex].mod.weapons[weaponIndex].znName + '?',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
            deleteModWeapon(modList.value[modIndex].mod.name, modList.value[modIndex].mod.weapons[weaponIndex].znName)
            modList.value[modIndex].mod.weapons.splice(weaponIndex, 1)
            message.success('删除武器成功')
            console.log('删除武器成功 modList.value', modList.value)
            hasCreateWeapon.value = false
        },
    })
}

// 删除本地法术
const handleDeleteSpell = (modIndex: number, spellIndex: number) => {
    Modal.confirm({
        title: '提示',
        icon: createVNode(ExclamationCircleOutlined),
        content: '确认删除法术: ' + modList.value[modIndex].mod.spell[spellIndex].params.name + '?',
        okText: '确认',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
            deleteModSpell(modList.value[modIndex].mod.name, modList.value[modIndex].mod.spell[spellIndex].params.name)
            modList.value[modIndex].mod.spell.splice(spellIndex, 1)
            message.success('删除法术成功')
            console.log('删除法术成功 modList.value', modList.value)
            hasCreateSpell.value = false
        },
    })
}

// 添加新武器
const handleCreateNewWeapon = (index: number) => {
    if (hasCreateWeapon.value && targetEditWeaponIndex.value == -1) {
        targetEditModIndex.value = -1
        hasCreateWeapon.value = false
        return
    }
    targetEditModIndex.value = index
    targetEditWeaponIndex.value = -1
    targetCreateNewWeapon.value = true
    let p = initWeaponFormState()
    Object.keys(p).forEach((key: string) => {
        formState[key] = p[key]
    })
    miriruBuffList.value = initMiriruBuffList()
    hasCreateWeapon.value = true
    hasCreateSpell.value = false
}

// 添加新技能 弹窗
const handleCreateNewSpellModal = (index: number) => {
    targetEditModIndex.value = index
    targetCreateNewSpell.value = true
    showCreateSpell.value = true
}

// 添加新技能 弹窗确认
const handleCreateNewSpell = () => {
    let type = createSpellFormState.type
    if (!type) return message.error('请选择法术类型')
    showCreateSpell.value = false // 关闭弹窗
    hasCreateSpell.value = true // 显示自定义技能
    hasCreateWeapon.value = false // 隐藏自定义武器
    setTimeout(() => {
        SpellFromRef.value.init(type)
    }, 200)
}

const handleEditWeapon = (index: number, weaponIndex: number) => {
    console.log('handleEditWeapon index weaponIndex', index, weaponIndex)
    targetCreateNewWeapon.value = false
    if (targetEditModIndex.value == index && targetEditWeaponIndex.value == weaponIndex) {
        targetEditModIndex.value = -1
        targetEditWeaponIndex.value = -1
        hasCreateWeapon.value = false
        return
    }
    targetEditModIndex.value = index
    targetEditWeaponIndex.value = weaponIndex
    targetEditSpellIndex.value = -1
    let item = showList.value[index].mod.weapons[weaponIndex]
    item = JSON.parse(JSON.stringify(item))
    console.log('handleEditWeapon item',item)
    Object.keys(item).forEach((key: string) => {
        // 逐个进行赋值
        formState[key] = item[key]
    })
    console.log('handleEditWeapon formState.miriruBuffs',formState.miriruBuffs)
    // 根据formState.miriruBuffs 赋值 miriruBuffList
    if (formState.miriruBuffs && formState.miriruBuffs.length) {
        formState.miriruBuffs.forEach((i: any, buffIndex: number) => {
            let index = miriruBuffList.value.findIndex((item: any) => item.id == i.id)
            let item = miriruBuffList.value[index]
            miriruBuffList.value[index].on = true
            miriruBuffList.value[index].change = i.atkAddSelfRestraintChange || i.change // 兼容旧字段atkAddSelfRestraintChange 新版本使用change
            if (i.atkAddSelfRestraintChange) { // 兼容
                delete formState.miriruBuffs[buffIndex].atkAddSelfRestraintChange
                formState.miriruBuffs[buffIndex].change = miriruBuffList.value[index].change
            }
            if (item.id == 'atkAddSelfRestraint' || item.id == 'castAddSelfRestraint') {
                miriruBuffList.value[index].addSelfRestraintTip = i.addSelfRestraintTip || '你的行为已被注意到，你突然发现自己穿着[RESTRAINTNAME]！'
                miriruBuffList.value[index].power = i.power || 0
                miriruBuffList.value[index].restraintAssignBindTags = i.restraintAssignBindTags || []
                miriruBuffList.value[index].atkAddSelfRestraintAssignBindType = i.atkAddSelfRestraintAssignBindType
                miriruBuffList.value[index].isLock = i.isLock
                miriruBuffList.value[index].lockType = i.lockType
            }
            if (item.inputVal) {
                miriruBuffList.value[index].val = i.val
            }
            if (item.selectDamageType) {
                miriruBuffList.value[index].damageType = i.damageType
            }
            if (item.selectDresses) {
                miriruBuffList.value[index].dresses = i.dresses
            }
        })
        console.log('miriruBuffList',miriruBuffList.value)
    }
    hasCreateWeapon.value = true
    hasCreateSpell.value = false
}

const handleEditSpell = (index: number, spellIndex: number) => {
    console.log('handleEditSpell index spellIndex', index, spellIndex)
    targetCreateNewSpell.value = false
    if (targetEditModIndex.value == index && targetEditSpellIndex.value == spellIndex) {
        targetEditModIndex.value = -1
        targetEditSpellIndex.value = -1
        hasCreateSpell.value = false
        return
    }
    targetEditModIndex.value = index
    targetEditSpellIndex.value = spellIndex
    targetEditWeaponIndex.value = -1
    let item = showList.value[index].mod.spell[spellIndex]
    hasCreateSpell.value = true
    hasCreateWeapon.value = false
    console.log('handleEditSpell item',item)
    setTimeout(() => {
        SpellFromRef.value.loadSpellData(item)
    }, 200)
}

const importMod = () => {
    // 创建input dom 选择zip文件
    let input = document.createElement('input')
    input.type = 'file'
    input.multiple = false // 单选
    input.accept = '.zip' // 只接受zip文件
    input.onchange = (e: any) => {
        let file = e.target.files[0]
        if (file) {
            importWeaponModFile(file)
            .then((res: any) => {
                console.log('importMod res',res)
                importSaveMod(res)
                message.success('导入成功喵~')
                pageInit()
            })
        }
    }
    input.click()
}


const load = () => {
    // 从localStorage加载formState
    const savedFormState = localStorage.getItem('kdWeaponSave')
    if (savedFormState) {
        let formStateData = JSON.parse(savedFormState)
        // 逐个进行赋值
        for (let key in formStateData) {
            formState[key] = formStateData[key]
        }
        console.log('已加载暂存', formState)
    }
}

const onSubmit = () => {
    console.log('submit!', toRaw(formState));
}

const reset = () => {
    // 重置formState
}

// 在modList的法术列表中新增法术
const pushModListSpell = (spell: any) => {
    modList.value[targetEditModIndex.value].mod.spell.push(spell)
    console.log('pushModListSpell modList.value[targetEditModIndex.value].mod.spell', modList.value[targetEditModIndex.value].mod.spell)
}

const editModListSpell = (spell: any) => {
    console.log('editModListSpell targetEditSpellIndex spell', targetEditSpellIndex.value, spell)
    modList.value[targetEditModIndex.value].mod.spell[targetEditSpellIndex.value] = spell
}

const handleUploadMod = (index: number) => {
    console.log('modList',modList.value)
    Modal.confirm({
        title: '提示',
        icon: createVNode(ExclamationCircleOutlined),
        content: '模组在审核后会公示,请不要发布违规内容,确认发布?',
        okText: '确认',
        cancelText: '取消',
        onOk:() => {
            let modItem = modList.value[index]
            let uploadItem = JSON.parse(JSON.stringify(modItem))
            uploadItem.mod.weapons = modItem.mod.weapons.map((item: any) => {
                return formatWeaponInfo(item)
            })
            let uploadModInfo = {
                name: uploadItem.mod.name,
                author: uploadItem.mod.author,
                desc: uploadItem.mod.desc,
                uploadTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
                mod: uploadItem,
            } as any
            let params = { uploadModInfo: { ...uploadModInfo } }
            const handleUploadModInfo = (formData: any) => {
                fetch('uploadModInfo', params)
                .then((res: any) => {
                    console.log('上传mod信息成功 res')
                    let { id } = res
                    uploadMod(formData, id)
                    .then(() => {
                        message.success('发布成功~ 请耐心等待审核喵~')
                    })
                    .catch((err: any) => {
                        message.error('发布失败喵~')
                        console.log('handleUploadMod err',err)
                    })
                })
            }
            console.log('uploadModInfo',uploadModInfo)
            exportWeaponModFile(uploadModInfo, false, true)
            .then((formData: any) => {
                handleUploadModInfo(formData)
            })
        },
    })
}

const handleShowOtherMod = (show: boolean = true) => {
    targetEditModIndex.value = -1
    if (show) {
        modListLoading.value = true
        fetch('modList')
        .then((res: any) => {
            console.log('已审核列表 res',res)
            otherModList.value = res.map((item: any) => {
                item.OtherModName = `${item.name} - 作者：${item.author}`
                // 格式化返回结果
                let modItem = item.mod
                delete item.mod
                item = { ...item, ...modItem }
                if (item.mod && item.mod.weapons && item.mod.weapons.length) item.mod.weapons = formatImportWeaponsData(item.mod.weapons) // 格式化武器数据
                return item
            })
            console.log('otherModList',otherModList.value)
            showOtherMod.value = true
            hasCreateWeapon.value = false
            hasCreateSpell.value = false
        })
        .finally(() => {
            modListLoading.value = false
        })
    }
    else {
        showOtherMod.value = false
        hasCreateWeapon.value = false
        hasCreateSpell.value = false
    }
}

// 获取待审核列表
const fetchCheckList = () => {
    modListLoading.value = true
    fetch('checkList')
    .then((res: any) => {
        console.log('待审核列表 res',res)
        reviewModList.value = res.map((item: any) => {
            item.OtherModName = `${item.name} - 作者：${item.author}`
            // 格式化返回结果
            let modItem = item.mod
            delete item.mod
            item = { ...item, ...modItem }
            if (item.mod && item.mod.weapons && item.mod.weapons.length) item.mod.weapons = formatImportWeaponsData(item.mod.weapons) // 格式化武器数据
            return item
        })
        console.log('reviewModList',reviewModList.value)
        showOtherMod.value = true
        hasCreateWeapon.value = false
        hasCreateSpell.value = false
    })
    .finally(() => {
        modListLoading.value = false
    })
}

// 切换显示待审核列表和已审核列表
const handleShowReviewMod = () => {
    showReviewMod.value = !showReviewMod.value
    if (showReviewMod.value) { // 待审核
        fetchCheckList()
    }
    else handleShowOtherMod(true) // 已审核
}

// 审核通过
const checkModSuccess = (id: string) => {
    console.log('checkModSuccess id',id)
    modListLoading.value = true
    fetch('checkPass', { id })
    .then(() => {
        message.success('审核通过喵~')
        handleShowReviewMod()
    })
    .catch(() => {
        message.error('发生错误啦 联系我让本喵看看~')
    })
    .finally(() => {
        modListLoading.value = false
    })
}

// 社区mod列表 - 删除
const otherModListDelete = (id: string) => {
    console.log('otherModListDelete id',id)
    modListLoading.value = true
    fetch('deleteMod', { id })
    .then(() => {
        message.success('删除成功喵~')
        handleShowOtherMod(true)
    })
    .catch(() => {
        message.error('发生错误啦 联系我让本喵看看~')
    })
    .finally(() => {
        modListLoading.value = false
    })
}

// 审核 - 删除该审核
const checkModDelete = (id: string) => {
    console.log('checkModDelete id',id)
    modListLoading.value = true
    fetch('checkDelete', { id })
    .then(() => {
        message.success('删除成功喵~')
        fetchCheckList()
    })
    .catch(() => {
        message.error('发生错误啦 联系我让本喵看看~')
    })
    .finally(() => {
        modListLoading.value = false
    })
}
// 下载依赖mod
const downloadMiriruMod = () => {
    // 导入本地的压缩包文件 下载
    let url = isProduction ? '/miriruMod.zip' : 'src/assets/miriruMod.zip'
    // 创建下载链接
    const link = document.createElement('a');
    link.download = `miriruMod.zip`;
    link.href = url
    document.body.appendChild(link);
    link.click();
    // 清理资源
    setTimeout(() => {
        document.body.removeChild(link);
    }, 100);
}

// 页面初始化 读取本地mod
const pageInit = () => {
    resetOldSave()
    targetEditModIndex.value = -1
    let list = loadModList()
    modList.value = []
    list.map((item: any) => {
        modList.value.push(item)
    })
    console.log('pageInit 读取本地mod modList',modList.value)
}

onMounted(() => {
    pageInit()
})

</script>

<style lang="scss" scoped>
.kdModCreate {
    width: 100vw;
    height: 100vh;
    background: linear-gradient(-90deg, #d3eee0, #d3e6f2, #d8dbf7, #f4e8fa);
    .kdWeaponCreate {
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
    }
    .modList {
        margin-right: 3vmin;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        .modListBox {
            height: 80vmin;
            width: 40vmin;
            background: #fff;
            border-radius: 1vmin;
            position: relative;
            padding: 0 0 10vmin;
            .buttons {
                height: 10vmin;
                position: absolute;
                bottom: 0;
                left: 0;
                width: 100%;
            }
            .button {
                background: #1677ff;
                color: #fff;
                padding: 1vmin 2vmin;
                border-radius: 0.5vmin;
                font-size: 1.5vmin;
                cursor: pointer;
            }
            .modClassTitle {
                font-weight: 600;
                font-size: 1.6vmin;
            }
            .modWeaponItem {
                border-bottom: 1px solid #ccc;
                cursor: pointer;
                position: relative;
                overflow: hidden;
                padding: 1vmin;
                min-height: 6vmin;
            }
            .weaponImg {
                width: 5vmin;
                height: 5vmin;
                border-radius: 50%;
                object-fit: cover;
                margin-right: 1vmin;
            }
        }
    }
    .title {
        font-size: 3vmin;
        font-weight: bold;
        margin-bottom: 3vmin;
    }
    .form {
        background: #fff;
        border-radius: 1vmin;
        width: 90vmin;
        height: 80vmin;
        overflow-y: scroll;
        padding: 6vmin 4vmin 0;
        position: relative;
    }
    .formTitle {
        font-size: 2vmin;
        font-weight: bold;
        margin-bottom: 2vmin;
    }
    .buttonList {
        margin: 0 auto;
        display: flex;
        align-items: center;
        justify-content: space-evenly;
        margin-top: 3vmin;
        position: sticky;
        bottom: 0;
        left: 0;
        background: #fff;
        width: 100%;
        padding: 2vmin 0;
        .button {
            min-width: 14vmin;
            background: #1677ff;
            color: #fff;
            padding: 1vmin;
            border-radius: 0.5vmin;
            font-size: 1.5vmin;
            cursor: pointer;
        }
    }
    .offhandBox {
        .offhandItem {
            .button {
                background: #1677ff;
                color: #fff;
                font-size: 1.5vmin;
                height: 4vmin;
                padding: 1vmin;
                margin-left: 1vmin;
                border-radius: 0.5vmin;
                flex-shrink: 0;
                cursor: pointer;
            }
        }
    }
    .miriruBuffListItem {
        margin-top: 2vmin;
        .buffItemTitle {
            font-size: 1.8vmin;
            font-weight: 600;
            color: #333;
            flex-shrink: 0;
        }
    }
    .offhandBuff {
        font-size: 2vmin;
        margin-bottom: 1vmin;
        span {
            margin-right: 1vmin;
        }
        .offhandBuffRemove {
            background: #1677ff;
            color: #fff;
            font-size: 1.5vmin;
            height: 4vmin;
            padding: 1vmin;
            margin-left: 1vmin;
            border-radius: 0.5vmin;
            flex-shrink: 0;
        }
    }
}
.link {
    color: #1677ff;
}
.numberBox {
    width: 100%;
}
.imageSelectList {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 1vmin;
    height: 60vmin;
    width: 100%;
    overflow-y: scroll;
    .imageSelectItem {
        width: 10vmin;
        height: 10vmin;
        border-radius: 1vmin;
        overflow: hidden;
        border: 1px solid #ccc;
        img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
    }
}
.tip {
    color: #999;
    font-size: 1.5vmin;
}
.download {
    font-size: 2vmin;
    color: #1677ff;
    text-decoration: underline;
    cursor: pointer;
}
.tipButton {
    cursor: pointer;
    svg {
        width: 3vmin;
        height: 3vmin;
    }
}


/* 四条光带基础样式 */
.light-bar {
    position: absolute;
    background: linear-gradient(90deg, transparent, rgba(255, 77, 240), transparent);
    transition: all 0.3s;
    opacity: 0;
    &.show {
        opacity: 1;
    }
    &.light1 {
        width: 100%;
        height: 1px;
        top: 0;
        left: 0;
        animation: flow-top 1s linear infinite;
    }
    &.light2 {
        width: 1px;
        height: 100%;
        top: 0;
        right: 0;
        animation: flow-right 1s linear infinite;
        animation-delay: 0.5s;
    }
    &.light3 {
        width: 100%;
        height: 1px;
        bottom: 0;
        right: 100%;
        animation: flow-bottom 1s linear infinite;
        animation-delay: 1s;
    }
    &.light4 {
        width: 1px;
        height: 100%;
        bottom: 100%;
        left: 0;
        animation: flow-left 1s linear infinite;
        animation-delay: 1.5s;
    }
}

/* 四条光带动画 */
@keyframes flow-top {
    0% {
        left: -100%;
    }
    100% {
        left: 100%;
    }
}
@keyframes flow-right {
    0% {
        top: -100%;
    }
    100% {
        top: 100%;
    }
}
@keyframes flow-bottom {
    0% {
        right: -100%;
    }
    100% {
        right: 100%;
    }
}
@keyframes flow-left {
    0% {
        bottom: -100%;
    }
    100% {
        bottom: 100%;
    }
}
</style>
